from symbide import LogManager
from symbide.src.utils import deleteTempPlots

import gtk

from widgetOrganizer import WidgetOrganizer 
from notebook import Notebook 
from toolbar import MainToolbar 
from menu import MainMenu
from find import Find
from statusbar import StatusBar


class MainWindow(WidgetOrganizer, gtk.Window):
    """
    The toplevel window of symbide.
    """
    
    def __init__(self):
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
        WidgetOrganizer.__init__(self, 'MainWindow')
        
        self.connect('delete_event', self._event_quit)
        
        #TODO: capture the size of the last session
        self.resize(600, 500)
        
        self.setTitle()
        
        # create VBox-widget
        VBox = gtk.VBox()
        VBox.show()
        self.add(VBox)
        
        # create subwidgets
        children = StatusBar(self), Find(self), Notebook(self), MainToolbar(self), MainMenu(self)
        expand = False, False, True, False, False
        
        for i in range(len(children)):
            self.addChild(children[i])
            VBox.pack_end(children[i], expand=expand[i])
        LogManager('Ready')
         
    def _event_quit(self, *args):
        """
        Closes all children in the widget tree, but gives them time to clean up.
        
        First asks for saving any changings, if this is done and the user hasn't
        aborted, stores the open worksheets for the next session. Afterwards it
        removes the widgetTree and gives widgets a chance to react.
        """
        LogManager('Closing')
        close = self.getChildren('Notebook').saveChangedSheets()
        if close:
            gtk.main_quit()
            self.getChildren('Notebook').storeSheets()
            self.removeChild()
            deleteTempPlots()
        else:
            #if the user aborts the closing, capture the event
            LogManager('Ready')
            return True
        
    def setTitle(self):
        """
        Sets the title of the main window to "Symbide - " + the name of the
        active worksheet.
        """
        notebook = self.getChildren('Notebook')
        if not notebook:
            self.set_title('Symbide')
            return
        sheet = notebook.get_current_sheet()
        if not sheet:
            self.set_title('Symbide')
            return
        self.set_title('Symbide - '+sheet.caption)
            
            
                        

def run():
    '''
    Creates the toplevel window, enables threads and enters the mainloop.
    '''
    
    m = MainWindow()
    gtk.gdk.threads_init()
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
